<template>
  <div class="stats-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>航班起降架次统计</h3>
          <div class="header-toolbar">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              @change="handleDateChange"
            />
            <el-button
              type="primary"
              @click="fetchData"
              :loading="loading"
            >
              查询
            </el-button>
          </div>
        </div>
      </template>

      <div class="chart-area">
        <div class="chart-container" ref="chartDom" v-loading="loading"></div>
        <div class="summary-cards">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-value">{{ summaryData.totalFlights }}</div>
              <div class="stat-name">总起降架次</div>
            </div>
          </el-card>
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-value">{{ summaryData.avgDailyFlights }}</div>
              <div class="stat-name">日均架次</div>
            </div>
          </el-card>
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-value">{{ summaryData.maxFlightsDay }}</div>
              <div class="stat-name">高峰日</div>
            </div>
          </el-card>
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-value">{{ summaryData.maxFlightsCount }}</div>
              <div class="stat-name">高峰日架次</div>
            </div>
          </el-card>
        </div>
      </div>

      <div class="data-details" v-if="flightData.length > 0">
        <h4>详细数据：{{ currentSelectedDate || flightData[0].flight_date }}</h4>
        <div class="detail-item">
          <span class="label">到达架次：</span>
          <span class="value">{{ currentData.arrivals || 0 }}</span>
        </div>
        <div class="detail-item">
          <span class="label">起飞架次：</span>
          <span class="value">{{ currentData.departures || 0 }}</span>
        </div>
        <div class="detail-item">
          <span class="label">总计：</span>
          <span class="value">{{ (currentData.arrivals || 0) + (currentData.departures || 0) }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

// 图表相关
const chartDom = ref(null)
let chartInstance = null
const loading = ref(false)
const currentSelectedDate = ref('')

// 日期范围 - 修改为固定显示2017-06-01到2017-06-10
const dateRange = ref([
  '2017-06-01',
  '2017-06-10'
])

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 处理日期变化
const handleDateChange = () => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择完整的日期范围')
    return
  }

  const [start, end] = dateRange.value
  const daysDiff = dayjs(end).diff(dayjs(start), 'day')

  if (daysDiff > 31) {
    ElMessage.warning('查询时间范围不能超过31天')
    dateRange.value = [start, dayjs(start).add(31, 'day').format('YYYY-MM-DD')]
  }
}

// 统计数据
const flightData = ref([])
const summaryData = ref({
  totalFlights: 0,
  avgDailyFlights: 0,
  maxFlightsDay: '',
  maxFlightsCount: 0
})

// 当前选中日期的数据
const currentData = computed(() => {
  return flightData.value.find(item => item.flight_date === currentSelectedDate.value) ||
    (flightData.value[0] || { arrivals: 0, departures: 0 })
})

// 初始化图表
const initChart = () => {
  if (!chartDom.value) return

  chartInstance = echarts.init(chartDom.value)

  chartInstance.on('click', (params) => {
    if (params.componentType === 'series') {
      currentSelectedDate.value = params.name
    }
  })

  const updateChart = () => {
    const option = {
      title: {
        text: `航班起降架次统计（${dateRange.value[0]} 至 ${dateRange.value[1]}）`,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          const date = params[0].axisValue
          const data = flightData.value.find(item => item.flight_date === date)
          return `
            <div style="font-weight:bold;margin-bottom:5px">${date}</div>
            <div style="display:flex;align-items:center">
              <span style="display:inline-block;width:10px;height:10px;background:#67C23A;margin-right:5px"></span>
              到达架次: ${data.arrivals}
            </div>
            <div style="display:flex;align-items:center">
              <span style="display:inline-block;width:10px;height:10px;background:#409EFF;margin-right:5px"></span>
              起飞架次: ${data.departures}
            </div>
            <div style="margin-top:5px">总计: ${data.arrivals + data.departures}</div>
          `
        }
      },
      legend: {
        data: ['到达架次', '起飞架次'],
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: flightData.value.map(item => item.flight_date),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '架次'
      },
      series: [
        {
          name: '到达架次',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: '#67C23A'
          },
          itemStyle: {
            color: '#67C23A'
          },
          data: flightData.value.map(item => item.arrivals)
        },
        {
          name: '起飞架次',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: '#409EFF'
          },
          itemStyle: {
            color: '#409EFF'
          },
          data: flightData.value.map(item => item.departures)
        }
      ]
    }

    chartInstance.setOption(option)
  }

  updateChart()

  // 使用防抖处理resize事件
  let resizeTimer = null
  const handleResize = () => {
    clearTimeout(resizeTimer)
    resizeTimer = setTimeout(() => {
      try {
        chartInstance?.resize()
      } catch (error) {
        console.error('图表resize错误:', error)
      }
    }, 100)
  }

  // 使用window的resize事件替代ResizeObserver
  window.addEventListener('resize', handleResize)

  // 返回清理函数
  return () => {
    clearTimeout(resizeTimer)
    window.removeEventListener('resize', handleResize)
  }
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true

    if (!dateRange.value || dateRange.value.length !== 2) {
      ElMessage.warning('请选择日期范围')
      return
    }

    const [startDate, endDate] = dateRange.value
    const response = await request({
      url: '/flight/statistics/daily-flights',
      method: 'get',
      params: {
        startDate,
        endDate
      }
    })

    flightData.value = response
    currentSelectedDate.value = flightData.value[0]?.flight_date || ''

    calculateSummaryData()

    if (chartInstance) {
      chartInstance.dispose()
    }
    initChart()
  } catch (error) {
    console.error('获取航班统计数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 计算汇总数据
const calculateSummaryData = () => {
  if (!flightData.value || flightData.value.length === 0) {
    summaryData.value = {
      totalFlights: 0,
      avgDailyFlights: 0,
      maxFlightsDay: '无数据',
      maxFlightsCount: 0
    }
    return
  }

  let totalArrivals = 0
  let totalDepartures = 0
  let maxFlightsCount = 0
  let maxFlightsDay = ''

  flightData.value.forEach(item => {
    totalArrivals += item.arrivals
    totalDepartures += item.departures

    const dailyTotal = item.arrivals + item.departures
    if (dailyTotal > maxFlightsCount) {
      maxFlightsCount = dailyTotal
      maxFlightsDay = item.flight_date
    }
  })

  const totalFlights = totalArrivals + totalDepartures
  const days = flightData.value.length

  summaryData.value = {
    totalFlights: totalFlights.toLocaleString(),
    avgDailyFlights: Math.round(totalFlights / days),
    maxFlightsDay: maxFlightsDay,
    maxFlightsCount: maxFlightsCount
  }
}

// 生命周期钩子
onMounted(() => {
  fetchData()
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
/* 新增样式 */
.header-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 调整日期选择器宽度 */
:deep(.el-date-editor--daterange) {
  width: 350px;
}
.stats-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-toolbar {
  display: flex;
  gap: 10px;
  align-items: center;
}

.chart-area {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  flex: 1;
  height: 450px;
  background: #f9fafc;
  border-radius: 4px;
}

.summary-cards {
  width: 300px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.stat-card {
  text-align: center;
  padding: 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-name {
  color: #909399;
  font-size: 14px;
}

.data-details {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.data-details h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #606266;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-item .label {
  color: #606266;
}

.detail-item .value {
  font-weight: bold;
}

.footer {
  text-align: right;
  margin-top: 10px;
}

.data-source {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}
</style>
